<template>
	<div class="sc-upload-file">
		<el-upload
			:disabled="disabled"
			:auto-upload="autoUpload"
			:action="action"
			:name="name"
			:data="data"
			:http-request="request"
			v-model:file-list="defaultFileList"
			:show-file-list="showFileList"
			:drag="drag"
			:accept="accept"
			:multiple="multiple"
			:limit="limit"
			:objName="objName"
			:orgCode="orgCode"
			:before-upload="before"
			:on-success="success"
			:on-error="error"
			:on-preview="handlePreview"
			:on-exceed="handleExceed"
		>
			<slot>
				<el-button type="primary" :disabled="disabled"
					>Click to upload</el-button
				>
			</slot>
			<template #tip>
				<div v-if="tip" class="el-upload__tip">{{ tip }}</div>
			</template>
		</el-upload>
		<span style="display: none !important"
			><el-input v-model="value"></el-input
		></span>
	</div>
</template>

<script>
import config from "@/config/upload";

export default {
	props: {
		modelValue: { type: [String, Array], default: "" },
		tip: { type: String, default: "" },
		action: { type: String, default: "" },
		apiObj: { type: Object, default: () => {} },
		name: { type: String, default: config.filename },
		data: { type: Object, default: () => {} },
		accept: { type: String, default: "" },
		maxSize: { type: Number, default: config.maxSizeFile },
		limit: { type: Number, default: 0 },
		objName: { type: String, default: "" },
		orgCode: { type: String, default: "" },
		autoUpload: { type: Boolean, default: true },
		showFileList: { type: Boolean, default: true },
		drag: { type: Boolean, default: false },
		multiple: { type: Boolean, default: true },
		disabled: { type: Boolean, default: false },
		onSuccess: {
			type: Function,
			default: () => {
				return true;
			},
		},
	},
	data() {
		return {
			value: "",
			defaultFileList: [],
		};
	},
	watch: {
		modelValue(val) {
			if (Array.isArray(val)) {
				if (
					JSON.stringify(val) !=
					JSON.stringify(this.formatArr(this.defaultFileList))
				) {
					this.defaultFileList = val;
					this.value = val;
				}
			} else {
				if (val != this.toStr(this.defaultFileList)) {
					this.defaultFileList = this.toArr(val);
					this.value = val;
				}
			}
		},
		defaultFileList: {
			handler(val) {
				this.$emit(
					"update:modelValue",
					Array.isArray(this.modelValue)
						? this.formatArr(val)
						: this.toStr(val)
				);
				this.value = this.toStr(val);
			},
			deep: true,
		},
	},
	mounted() {
		this.defaultFileList = Array.isArray(this.modelValue)
			? this.modelValue
			: this.toArr(this.modelValue);
		this.value = this.modelValue;
	},
	methods: {
		//默认值转换为数组
		toArr(str) {
			var _arr = [];
			var arr = str.split(",");
			arr.forEach((item) => {
				if (item) {
					var urlArr = item.split("/");
					var fileName = urlArr[urlArr.length - 1];
					_arr.push({
						name: fileName,
						url: item,
					});
				}
			});
			return _arr;
		},
		//数组转换为原始值
		toStr(arr) {
			return arr.map(v => v.url).join(",")
			// eslint-disable-next-line no-debugger
			// //debugger;
			// let aa = arr
			// 	.map((v) => {
			// 		// eslint-disable-next-line no-debugger
			// 		////debugger;
			// 		let ss = v;
			// 		console.log(ss);
			// 		return v.realUrl && v.realUrl.length > 2
			// 			? v.realUrl
			// 			: v.url;
			// 	})
			// 	.join(",");
			// return aa;
			//return arr.map((v) => (v.realUrl&&v.realUrl.length>2 ? v.realUrl : v.url)).join(",");
		},
		//格式化数组值
		formatArr(arr) {
			var _arr = [];
			arr.forEach((item) => {
				if (item) {
					_arr.push({
						name: item.name,
						url: item.url,
					});
				}
			});
			return _arr;
		},
		before(file) {
			const maxSize = file.size / 1024 / 1024 < this.maxSize;
			if (!maxSize) {
				this.$message.warning(
					`上传文件大小不能超过 ${this.maxSize}MB!`
				);
				return false;
			}
		},
		success(res, file) {
			var os = this.onSuccess(res, file);
			if (os != undefined && os == false) {
				return false;
			}
			if (res && res.opFlag == "1") {
				file.name = res.content.fileName;
				file.url ="http://"+res.content.urlPath;
				return false;
			}
		},
		error(err) {
			this.$notify.error({
				title: "上传文件未成功",
				message: err,
			});
		},
		beforeRemove(uploadFile) {
			return this.$confirm(`是否移除 ${uploadFile.name} ?`, "提示", {
				type: "warning",
			})
				.then(() => {
					return true;
				})
				.catch(() => {
					return false;
				});
		},
		handleExceed() {
			this.$message.warning(
				`当前设置最多上传 ${this.limit} 个文件，请移除后上传!`
			);
		},
		handlePreview(uploadFile) {
			window.open(uploadFile.url);
		},
		async request(param) {
			var apiObj = config.apiObjFile;
				if(this.apiObj){
					apiObj = this.apiObj;
				}
				var requestId = this.getFilelastModified();
				const data = new FormData();
				//data.append(param.filename, param.file);
				data.append("data", param.file);
				// data.append("data", param.file);
				data.append("requestId", requestId);
				data.append("total", 1);
				data.append("index", 0);
				data.append("fileName", param.file.name);
				data.append("fileType", param.file.type);
				data.append("objName", this.objName);
				data.append("orgCode", this.orgCode);
				apiObj.post(data, {
					onUploadProgress: e => {
						const complete = parseInt(((e.loaded / e.total) * 100) | 0, 10)
						param.onProgress({percent: complete})
					}
				}).then(res => {
					if (res&&res.opFlag&&res.opFlag == "1") {
						param.onSuccess(res);
						return;
					}else{
						//param.onError("上传失败");
					}
				}).catch(err => {
					param.onError(err)
				})
			// eslint-disable-next-line no-debugger
			//debugger;
			// var apiObj = config.apiObjFile;
			// if (this.apiObj) {
			// 	apiObj = this.apiObj;
			// }
			// var requestId = this.getFilelastModified();
			// //上传文件单片2MB
			// var chunkSize = 1024 * 1024 * 2;
			// // 总分片数量
			// var chunks = Math.ceil(param.file.size / chunkSize);
			// for (let index = 0; index < chunks; index++) {
			// 	var tempFile = null;
			// 	if (index === chunks - 1) {
			// 		tempFile = param.file.slice(index * chunkSize);
			// 	} else {
			// 		tempFile = param.file.slice(
			// 			index * chunkSize,
			// 			(index + 1) * chunkSize
			// 		);
			// 	}
			// 	if (index > 0)
			// 		// eslint-disable-next-line no-debugger
			// 		//debugger;
			// 	const data = new FormData();
			// 	data.append("data", tempFile);
			// 	// data.append("data", param.file);
			// 	data.append("requestId", requestId);
			// 	data.append("total", chunks);
			// 	data.append("index", index);
			// 	data.append("fileName", param.file.name);
			// 	data.append("fileType", param.file.type);
			// 	data.append("objName", this.objName);
			// 	data.append("orgCode", this.orgCode);
			// 	for (const key in param.data) {
			// 		data.append(key, param.data[key]);
			// 	}
			// 	await apiObj
			// 		.post(data, {
			// 			onUploadProgress: (e) => {
			// 				const complete = parseInt(
			// 					(((index + 1) * 100) / chunks) | 0,
			// 					10
			// 				);
			// 				console.log(e.loaded, e.total);
			// 				param.onProgress({ percent: complete });
			// 			},
			// 		})
			// 		.then((res) => {
			// 			// eslint-disable-next-line no-debugger
			// 			////debugger
			// 			if (res.opFlag == "0") {
			// 				param.onError("上传失败");
			// 				return;
			// 			} else {
			// 				param.onSuccess(res);
			// 			}
			// 		})
			// 		.catch((err) => {
			// 			param.onError(err);
			// 			return;
			// 		});
			//}
		},
		getFilelastModified: function () {
			var dd = new Date();
			return (
				dd.getFullYear().toString() +
				dd.getMonth().toString() +
				dd.getDate().toString() +
				dd.getHours().toString() +
				dd.getMinutes().toString() +
				dd.getSeconds().toString() +
				dd.getMilliseconds().toString()
			);
		},
	},
};
</script>

<style scoped>
.el-form-item.is-error .sc-upload-file:deep(.el-upload-dragger) {
	border-color: var(--el-color-danger);
}
.sc-upload-file {
	width: 100%;
}
.sc-upload-file:deep(.el-upload-list__item) {
	transition: none !important;
}
</style>
